package com.shchekoldin.server;

import com.beust.jcommander.JCommander;
import com.shchekoldin.server.util.CmdOptions;
import com.shchekoldin.server.util.Configuration;
import com.shchekoldin.server.util.FileContentReader;
import org.apache.log4j.*;
import org.slf4j.LoggerFactory;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

public class Application {
    
    private static final String LOGGER_PATTERN = "%d [%t] %p %c.%x%M: %m%n";

    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Application.class);

    private static Configuration configuration = null;

    // -------------------------------------------------------
    // LOGIC
    // -------------------------------------------------------

    private static void configureLogger(boolean debug) {
        Logger logger = Logger.getRootLogger();
        logger.setLevel(debug ? Level.DEBUG : Level.INFO);
        ConsoleAppender appender = new ConsoleAppender(new PatternLayout(LOGGER_PATTERN));
        logger.addAppender(appender);
    }

    private static boolean loadConfiguration(String fileName) {
        try {
            String fileContent = FileContentReader.run(fileName);
            StringReader stringReader = new StringReader(fileContent);

            JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

            configuration = (Configuration) unmarshaller.unmarshal(stringReader);
        } catch (Exception e) {
            LOGGER.error("Can't parse config xml file", e);
            return false;
        }

        return true;
    }
    
    //
    // API
    //

    public static void main(String[] args) throws Exception {
        CmdOptions cmdOptions = new CmdOptions();
        new JCommander(cmdOptions, args);

        configureLogger(cmdOptions.isDebug());

        if (loadConfiguration(cmdOptions.getConfigFileName())) {
            (new JettyServer()).run();
        }
    }

    // -------------------------------------------------------
    // GET & SET
    // -------------------------------------------------------

    public static Configuration getConfiguration() {
        return configuration;
    }

}
